import { createRouter, createWebHistory } from 'vue-router'
//导入组件
import LoginVue from '@/views/Login.vue'

import useUserInfoStore from '@/stores/userInfo.js'

import EditExamVue from '@/views/user/teacher/EditExam.vue'
import ExamListVue from '@/views/user/teacher/ExamList.vue'
import UserInfoVue from '@/views/user/UserInfo.vue'
import UserResetPasswordVue from '@/views/user/UserResetPassword.vue'
import TeacherListVue from '@/views/user/admin/TeacherList.vue'
import StudentExamListVue from '@/views/user/student/studentExamList.vue'
// import SystemListVue from '@/views/user/admin/SystemList.vue'
import TeacherLayoutVue from '@/views/user/teacher/TeacherLayout.vue'
import AdminLayoutVue from '@/views/user/admin/AdminLayout.vue'
import StudentLayoutVue from '@/views/user/student/StudentLayout.vue'
import NoPermission from '@/views/NoPermission.vue'



//定义路由关系
const routes = [
    { path: '/login', component: LoginVue,},
    {
        path: '/', component: TeacherLayoutVue, redirect: '/login',meta: { requiresRole:0 },
        children: [
            { path: '/teacher/home', component: ExamListVue, },
            { path: '/teacher/info', component: UserInfoVue, },
            { path: '/teacher/resetPassword', component: UserResetPasswordVue, },
            { path: '/teacher/examEdit', component: EditExamVue,}
        ]
    },
    {
        path: '/', component: StudentLayoutVue,meta: { requiresRole: 'student' },
        children: [
          {path: '/student/home', component: StudentExamListVue,},
          {path: '/student/info', component: UserInfoVue,}
          
        ]
    },
    {
        path: '/', component: AdminLayoutVue,meta: { requiresRole: 1 },
        children: [
            {path: '/admin/home', component: TeacherListVue},
            { path: '/admin/info', component: UserInfoVue, },
            

        ]
    },
    {
        path: '/no-permission',
        component: NoPermission,
    },
    
]

//创建路由器
const router = createRouter({
    history: createWebHistory(),
    routes: routes
})

router.beforeEach((to, from, next) => {
    // 获取目标路由的权限要求
    console.log('to.matched:', to.matched);
    const userInfoStore = useUserInfoStore();
    const requiredRole = to.matched.some(record => record.meta.requiresRole);
    const requiredStudentRole = to.matched.find(record => record.meta && record.meta.requiresRole)?.meta.requiresRole;
    //如果没有权限要求，直接允许访问
    if (to.path === '/login') {
      next();
      return
  }

  if (requiredRole === undefined) {
    next();
    return;
}
    
    // 根据用户的 role 判断是否允许访问
    if (userInfoStore.info.role == requiredRole||userInfoStore.info.role == requiredStudentRole) {
      // 如果用户角色匹配，允许访问
      next();
    } else if (userInfoStore.info.role == 1 && (requiredRole == 0 || requiredRole ==1)) {
      // 如果用户是管理员，允许访问教师和管理员页面
      next();
    } else {
      // 如果用户没有权限，重定向到无权限页面
      next('/no-permission');
    }
  });

//导出路由
export default router
